package com.jdone.compus.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import com.google.zxing.client.j2se.MatrixToImageWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;

import java.io.ByteArrayOutputStream;

public class QRCodeGenerator {

   /* *//**
     * 生成高清彩色二维码，中心大 Logo，输出 Base64
     *
     * @param logoPercent Logo 占比 (0.3 ~ 0.4)
     * @param content     二维码内容
     * @param qrSize      最终二维码像素尺寸（建议 ≥600）
     * @param v
     * @param qrColor     二维码点阵颜色 (ARGB)，例如 0xFF112233
     * @param bgColor     背景颜色 (ARGB)，例如 0xFFFFFFFF
     *//*
    public static String generateHighDefColoredQRCode(String content,
                                                      int qrSize,
                                                      float logoPercent,
                                                      int qrColor,
                                                      int bgColor) throws Exception {
        // —— 1. 编码参数 ——
        Hashtable<EncodeHintType,Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        // —— 2. 生成 BitMatrix ——
        BitMatrix matrix = new MultiFormatWriter()
                .encode(content, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);

        // —— 3. 彩色渲染 ——
        MatrixToImageConfig cfg = new MatrixToImageConfig(qrColor, bgColor);
        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix, cfg);

        // —— 4. 读取 Logo ——
        Path root = Paths.get("").toAbsolutePath();
        File logoFile = root.resolve("upload").resolve("logo.png").toFile();
        if (!logoFile.exists()) {
            throw new FileNotFoundException("Logo 文件不存在: " + logoFile.getAbsolutePath());
        }
        BufferedImage logo = ImageIO.read(logoFile);
        if (logo == null) {
            throw new IOException("无法读取 Logo，请检查格式或插件支持：" + logoFile.getAbsolutePath());
        }

        // —— 5. 双三次高质量缩放 Logo ——
        int logoSize = Math.round(qrSize * logoPercent);
        BufferedImage scaledLogo = new BufferedImage(logoSize, logoSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gLogo = scaledLogo.createGraphics();
        gLogo.setRenderingHint(RenderingHints.KEY_INTERPOLATION,    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        gLogo.setRenderingHint(RenderingHints.KEY_RENDERING,        RenderingHints.VALUE_RENDER_QUALITY);
        gLogo.setRenderingHint(RenderingHints.KEY_ANTIALIASING,     RenderingHints.VALUE_ANTIALIAS_ON);
        AffineTransform at = AffineTransform.getScaleInstance(
                logoSize / (double)logo.getWidth(),
                logoSize / (double)logo.getHeight()
        );
        gLogo.drawRenderedImage(logo, at);
        gLogo.dispose();

        // —— 6. 合成到中心 ——
        Graphics2D g = qrImage.createGraphics();
        // 可选：白色圆角底让 Logo 更突出
        int padding = Math.round(logoSize * 0.1f);
        int x = (qrSize - logoSize) / 2, y = x;
        g.setColor(Color.WHITE);
        g.fillRoundRect(x - padding, y - padding,
                logoSize + padding*2, logoSize + padding*2,
                padding, padding);
        // 再贴 Logo
        g.drawImage(scaledLogo, x, y, null);
        g.dispose();

        // —— 7. 输出 Base64 ——
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(qrImage, "PNG", baos);
            return Base64.encodeBase64String(baos.toByteArray());
        }
    }*/

    /*public static String generateHighDefColoredQRCode(String content,
                                                      int qrSize,
                                                      float logoPercent,
                                                      int qrColor,
                                                      int bgColor) throws Exception {
        // —— 0. 拼接完整的支付 URL ——
        // 传入的 content 约定为 id，比如 "2"
        String fullUrl = "https://wsh.swpu.edu.cn/shareh5/#/payment?id=" + content;

        // —— 1. 编码参数 ——
        Hashtable<EncodeHintType,Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        // —— 2. 生成 BitMatrix ——
        BitMatrix matrix = new MultiFormatWriter()
                .encode(fullUrl, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);

        // —— 3. 彩色渲染 ——
        MatrixToImageConfig cfg = new MatrixToImageConfig(qrColor, bgColor);
        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix, cfg);

        // —— 4. 读取 Logo ——
        Path root = Paths.get("").toAbsolutePath();
        File logoFile = root.resolve("upload").resolve("logo.png").toFile();
        if (!logoFile.exists()) {
            throw new FileNotFoundException("Logo 文件不存在: " + logoFile.getAbsolutePath());
        }
        BufferedImage logo = ImageIO.read(logoFile);
        if (logo == null) {
            throw new IOException("无法读取 Logo，请检查格式或插件支持：" + logoFile.getAbsolutePath());
        }

        // —— 5. 双三次高质量缩放 Logo ——
        int logoSize = Math.round(qrSize * logoPercent);
        BufferedImage scaledLogo = new BufferedImage(logoSize, logoSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gLogo = scaledLogo.createGraphics();
        gLogo.setRenderingHint(RenderingHints.KEY_INTERPOLATION,    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        gLogo.setRenderingHint(RenderingHints.KEY_RENDERING,        RenderingHints.VALUE_RENDER_QUALITY);
        gLogo.setRenderingHint(RenderingHints.KEY_ANTIALIASING,     RenderingHints.VALUE_ANTIALIAS_ON);
        AffineTransform at = AffineTransform.getScaleInstance(
                logoSize / (double)logo.getWidth(),
                logoSize / (double)logo.getHeight()
        );
        gLogo.drawRenderedImage(logo, at);
        gLogo.dispose();

        // —— 6. 合成到中心 ——
        Graphics2D g = qrImage.createGraphics();
        int padding = Math.round(logoSize * 0.1f);
        int x = (qrSize - logoSize) / 2, y = x;
        g.setColor(Color.WHITE);
        g.fillRoundRect(x - padding, y - padding,
                logoSize + padding*2, logoSize + padding*2,
                padding, padding);
        g.drawImage(scaledLogo, x, y, null);
        g.dispose();

        // —— 7. 输出 Base64 ——
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(qrImage, "PNG", baos);
            return Base64.encodeBase64String(baos.toByteArray());
        }
    }*/

    public static String generateHighDefColoredQRCode(String content,
                                                      int qrSize,
                                                      float v, int qrColor,
                                                      int bgColor) throws Exception {
        // —— 0. 拼接完整的支付 URL ——
        String fullUrl = "https://wsh.swpu.edu.cn/shareh5/#/payment?id=" + content;

        // —— 1. 编码参数 ——
        Hashtable<EncodeHintType,Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        // —— 2. 生成 BitMatrix ——
        BitMatrix matrix = new MultiFormatWriter()
                .encode(fullUrl, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);

        // —— 3. 彩色渲染 ——
        MatrixToImageConfig cfg = new MatrixToImageConfig(qrColor, bgColor);
        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix, cfg);

        // —— 4. 输出 Base64 ——
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(qrImage, "PNG", baos);
            // 直接调用 Apache 的静态方法
            return Base64.encodeBase64String(baos.toByteArray());
        }
    }

}
